package com.tarena.luban.demo.gateway.filters;

import com.tarena.luban.demo.gateway.ex.GatewayException;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthenticationFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 验证 请求中凭据是否正确
        try{
            //token=0123456789
            checkToken(exchange);
        }catch (GatewayException e){
            //验证失败
            //return responseWrite(exchange,e);
            return Mono.error(e);
        }
        return chain.filter(exchange);
    }

    /*private Mono<Void> responseWrite(ServerWebExchange exchange,GatewayException e) {
        //准备返回的数据处理乱码,用响应输出
        String message=e.getMessage();
        //拿到响应对象
        ServerHttpResponse response = exchange.getResponse();
        //设置乱码 绝大多数浏览器支持application/json utf-8解码 提前到了UnicodFilter实现
        return response.writeWith(Mono.fromSupplier(() -> response.bufferFactory().wrap(message.getBytes(StandardCharsets.UTF_8))));
    }*/

    /**
     * 检查3中来源的token
     * queryParam ?token=123
     * Authorization头 123
     * Cookie头  token=123
     */
    private void checkToken(ServerWebExchange exchange) throws GatewayException{
        //1. 拿到请求对象
        ServerHttpRequest request = exchange.getRequest();
        //2. 取值
        String token=null;
        //3. param取值 ?不传 ?token没值 ?token=123
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        token=queryParams.getFirst("token");
        if (token==null){
            //4. Authorization 头取值
            token = request.getHeaders().getFirst("Authorization");
            if (token==null){
                //5. Cookie: token=123
                HttpCookie tokenCookie = request.getCookies().getFirst("token");
                if (tokenCookie!=null){
                    token=tokenCookie.getValue();
                }
            }
        }
        if (token==null){
            throw new GatewayException("你没有携带token凭证");
        }
        //非空的token 检验合法性 正则验证是否是10个数字
        boolean matches = token.matches("\\d{10}");
        if (!matches){
            throw new GatewayException("你的token不能解析");
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
